package com.party.core.service.wechat.impl;

import com.google.common.base.Strings;
import com.party.common.constant.WechatConstant;
import com.party.common.paging.Page;
import com.party.core.api.crowdfund.IAnalyzeService;
import com.party.core.dao.read.initsubscribe.InitSubscribeDao;
import com.party.core.dao.read.wechat.WechatSubscribeReadDao;
import com.party.core.dao.write.wechat.WechatSubscribeWriteDao;
import com.party.core.model.BaseModel;
import com.party.core.model.wechat.WechatSubscribe;
import com.party.core.service.wechat.IWechatSubscribeService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.sun.istack.NotNull;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 微信订阅接口实现
 * Created by wei.li
 *
 * @date 2017/8/31 0031
 * @time 18:11
 */
@Service
public class WechatSubscribeService implements IWechatSubscribeService {

    @Autowired
    private WechatSubscribeReadDao wechatSubscribeReadDao;

    @Autowired
    private WechatSubscribeWriteDao wechatSubscribeWriteDao;


    @Autowired
    private InitSubscribeDao initSubscribeDao;

    @Autowired
    IWechatOpenMemberService wechatOpenMemberService;

    @Autowired
    private IAnalyzeService analyzeService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 订阅插入
     * @param wechatSubscribe 微信订阅
     * @return 插入结果（true/false）
     */
    @Override
    public String insert(WechatSubscribe wechatSubscribe) {
        BaseModel.preInsert(wechatSubscribe);
        boolean result = wechatSubscribeWriteDao.insert(wechatSubscribe);
        if (result){
            return wechatSubscribe.getId();
        }
        return null;
    }

    /**
     * 微信订阅更新
     * @param wechatSubscribe 微信订阅
     * @return 更新结果（true/false）
     */
    @Override
    public boolean update(WechatSubscribe wechatSubscribe) {
        wechatSubscribe.setUpdateDate(new Date());
        return wechatSubscribeWriteDao.update(wechatSubscribe);
    }

    /**
     * 逻辑删除
     * @param id 实体主键
     * @return 删除结果（true/false）
     */
    @Override
    public boolean deleteLogic(@NotNull String id) {
        if (Strings.isNullOrEmpty(id)){
            return false;
        }
        return wechatSubscribeWriteDao.deleteLogic(id);
    }

    /**
     * 物理删除
     * @param id 实体主键
     * @return 删除结果（true/false）
     */
    @Override
    public boolean delete(@NotNull String id) {
        if (Strings.isNullOrEmpty(id)){
            return false;
        }
        return wechatSubscribeWriteDao.delete(id);
    }

    /**
     * 批量逻辑删除
     * @param ids 主键集合
     * @return 删除结果（true/false）
     */
    @Override
    public boolean batchDeleteLogic(@NotNull Set<String> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return false;
        }
        return wechatSubscribeWriteDao.batchDeleteLogic(ids);
    }

    /**
     * 批量物理删除
     * @param ids 主键集合
     * @return 删除结果（true/false）
     */
    @Override
    public boolean batchDelete(@NotNull Set<String> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return false;
        }
        return wechatSubscribeWriteDao.batchDelete(ids);
    }

    /**
     * 获取订阅信息
     * @param id 主键
     * @return 获取订阅信息
     */
    @Override
    public WechatSubscribe get(String id) {
        return wechatSubscribeReadDao.get(id);
    }

    /**
     * 是否订阅
     * @param appid 公众号编号
     * @param openId 订阅者编号
     * @return 是否订阅
     */
    @Override
    public boolean isSubscribe(String appid, String openId) {
        WechatSubscribe wechatSubscribe = this.get(appid, openId);
        if (null == wechatSubscribe){
            return false;
        }
        if (wechatSubscribe.getStatus().equals(WechatConstant.EVENT_TYPE_SUBSCRIBE)){
            return true;
        }
        return false;
    }

    /**
     * 获取订阅信息
     * @param appid 公众号编号
     * @param openid 订阅者编号
     * @return 订阅信息
     */
    @Override
    public WechatSubscribe get(String appid, String openid) {
        WechatSubscribe wechatSubscribe = new WechatSubscribe();
        wechatSubscribe.setAppid(appid);
        wechatSubscribe.setOpenid(openid);
        List<WechatSubscribe> list = this.list(wechatSubscribe);
        if (!CollectionUtils.isEmpty(list)){
            return list.get(0);
        }
        return null;
    }

    /**
     * 订阅
     * @param appid 公众号编号
     * @param openId 订阅者编号
     */
    @Override
    public void subscribe(String appid, String openId) {
        WechatSubscribe wechatSubscribe = this.get(appid, openId);
        if (null != wechatSubscribe){
            wechatSubscribe.setStatus(WechatConstant.EVENT_TYPE_SUBSCRIBE);
            this.update(wechatSubscribe);
        }
        else {
            wechatSubscribe = new WechatSubscribe();
            wechatSubscribe.setOpenid(openId);
            wechatSubscribe.setAppid(appid);
            wechatSubscribe.setStatus(WechatConstant.EVENT_TYPE_SUBSCRIBE);
            this.insert(wechatSubscribe);
        }

        this.updateAnalyzeSubscribeStatus(appid, openId, 1);
    }

    /**
     * 取消订阅
     * @param appid 公众号编号
     * @param openId 订阅者编号
     */
    @Override
    public void unSubscribe(String appid, String openId) {
        WechatSubscribe wechatSubscribe = this.get(appid, openId);
        if (null != wechatSubscribe){
            wechatSubscribe.setStatus(WechatConstant.EVENT_TYPE_UNSUBSCRIBE);
            this.update(wechatSubscribe);
            this.updateAnalyzeSubscribeStatus(appid, openId, 0);
        }
    }

    /**
     * 更新众筹分析表的是否关注字段
     * @param appid
     * @param openId
     * @param status: 0-否, 1-是
     */
    private void updateAnalyzeSubscribeStatus(String appid, String openId, int status) {
        try {
            int systemStatus = wechatOpenMemberService.getSystem().getAuthorizerAppid().equals(appid) ? 0 : 1;
            List<String> projectIds = initSubscribeDao.getProjectIdsByOpenidAndAppId(openId, appid, systemStatus);
            if (CollectionUtils.isEmpty(projectIds)) {
                return;
            }
            // 更新所有的众筹项目分析表的is_subscribe字段
            for (String projectId: projectIds) {
                //analyzeWriteDao.updateSubscribe(projectId, status);
                try {
                    analyzeService.updateSubscribe(projectId, status);
                } catch (Exception e) {
                    logger.error("异常", e);
                    continue;
                }
            }
        } catch (Exception e) {
            logger.error("更新众筹分析表的是否关注字段 异常", e);
        }
    }

    /**
     * 分页查询
     * @param wechatSubscribe 订阅信息
     * @param page 分页信息
     * @return 订阅列表
     */
    @Override
    public List<WechatSubscribe> listPage(WechatSubscribe wechatSubscribe, Page page) {
        return wechatSubscribeReadDao.listPage(wechatSubscribe, page);
    }

    /**
     * 查询所有
     * @param wechatSubscribe 订阅信息
     * @return 订阅列表
     */
    @Override
    public List<WechatSubscribe> list(WechatSubscribe wechatSubscribe) {
        return wechatSubscribeReadDao.listPage(wechatSubscribe, null);
    }

    @Override
    public List<WechatSubscribe> batchList(@NotNull Set<String> ids, WechatSubscribe wechatSubscribe, Page page) {
        return null;
    }
}
